from tencentcloud.ocr.v20181119.models import IDCardOCRResponse
from PyQt5.QtGui import QDesktopServices, QTextCursor, QPixmap
from PyQt5.QtWidgets import QMainWindow, QFileDialog, QApplication, QLabel
from .delay_task import ImgToPdfDelayTask, IdCardDetectTask
from PyQt5.QtCore import QThread, QUrl, Qt
from UI import Ui_smartToolWindow
from .dialog import AboutDialog

import settings as st


class SmartTools(QMainWindow, Ui_smartToolWindow):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.initWindow()
        self.bindSignal()
        self.initTask()

    def initWindow(self):
        self.setupUi(self)
        self.slider_frame_2.hide()
        self.show()

    def initTask(self):
        self.sec_thread = QThread()

        # IMG
        self.img_to_pdf_task = ImgToPdfDelayTask()
        self.img_to_pdf_task.moveToThread(self.sec_thread)
        # sec thread
        self.img_to_pdf_task.generating_signal.connect(self.generatingPdfEvent)
        self.img_to_pdf_task.scan_img_done_signal.connect(self.scanImgPathDoneEvent)
        self.img_to_pdf_task.exported_signal.connect(self.generatingPdfEvent)

        # ID CARD
        self.id_card_detect_task = IdCardDetectTask()
        self.id_card_detect_task.moveToThread(self.sec_thread)
        # main
        self.id_card_detect_task.detected_signal.connect(self.idCardDetectedEvent)
        self.sec_thread.start()

    def bindSignal(self):
        # menu
        self.conf_menu.triggered.connect(self.openIniDir)
        self.about_menu.triggered.connect(self.aboutEvent)

        # btn
        self.btn1.clicked.connect(self.imgToPdfBtnClickedEvent)
        self.btn1_s.clicked.connect(self.imgToPdfBtnClickedEvent)
        self.btn2.clicked.connect(self.toDetectIdCardEvent)
        self.btn2_s.clicked.connect(self.toDetectIdCardEvent)
        self.btn3.clicked.connect(self.toDoEvent)
        self.btn3_s.clicked.connect(self.toDoEvent)
        self.transform_btn.clicked.connect(self.imgToPdfGenerateClickedEvent)
        self.id_detected_btn.clicked.connect(self.idCardDetectBtnClickedEvent)

    @staticmethod
    def openIniDir():
        url = QUrl('file:///' + st.APP_DIR)
        QDesktopServices().openUrl(url)

    def aboutEvent(self):
        about_dialog = AboutDialog(self)
        about_dialog.setWindowModality(Qt.ApplicationModal)
        about_dialog.show()

    def toDetectIdCardEvent(self):
        self.stacked_widget.setCurrentWidget(self.p2)

    def toDoEvent(self):
        self.stacked_widget.setCurrentWidget(self.p3)

    def imgToPdfBtnClickedEvent(self):
        self.stacked_widget.setCurrentWidget(self.p1)

    def imgToPdfChoosePathClickedEvent(self):
        frame = QFileDialog.getExistingDirectory(self, '选择要转换为PDF的图像文件夹', st.DESKTOP_DIR)
        if frame:
            self.img_to_pdf_task.path_changed_signal.emit(frame)

    def scanImgPathDoneEvent(self, msg):

        self.log_widget.setText(msg)

        if not self.transform_btn.isEnabled():
            self.transform_btn.setEnabled(True)

    def imgToPdfGenerateClickedEvent(self):
        self.transform_btn.setEnabled(False)
        self.img_to_pdf_task.generate_pdf_signal.emit()

    def generatingPdfEvent(self, msg):
        self.log_widget.append(msg)
        self.log_widget.moveCursor(QTextCursor.End)

    def idCardChoosePathClickedEvent(self):
        card_file, card_format = QFileDialog.getOpenFileName(self, '选择身份证件图', st.DESKTOP_DIR, '证件图像(*.jpg *.png)')
        if card_file:
            self.id_card_detect_task.img_changed_signal.emit(card_file)
            if not self.id_detected_btn.isEnabled():
                self.id_detected_btn.setEnabled(True)

            pixmap = QPixmap(card_file)
            proportion = pixmap.width() / self.card_lb.width()
            pixmap.setDevicePixelRatio(proportion)
            self.card_lb.setPixmap(pixmap)

    def idCardDetectBtnClickedEvent(self):
        self.id_detected_btn.setEnabled(False)
        self.id_card_detect_task.detect_signal.emit()

    def idCardDetectedEvent(self, p):

        if isinstance(p, IDCardOCRResponse):
            self.id_name.setText(p.Name)
            self.id_sex.setText(p.Sex)
            self.id_mz.setText(p.Nation)
            self.id_birth.setText(p.Birth)
            self.id_addr.setText(p.Address)
            self.id_num.setText(p.IdNum)
            self.card_log.append(f'姓名: {p.Name}')
            self.card_log.append(f'性别: {p.Sex}, 民族: {p.Nation}')
            self.card_log.append(f'出生年月: {p.Birth}')
            self.card_log.append(f'地址: {p.Address}')
            self.card_log.append(f'证件号: {p.IdNum}')
            self.id_copy_btn.setEnabled(True)

        elif isinstance(p, str):
            self.card_log.append(p)
        else:
            self.card_log.append(f'{p}')

    def copyMultiIDCardMsg(self):
        cnt = f'{self.id_name.text()}\txxx\t{self.id_num.text()}\t{self.id_addr.text()}'
        clipboard = QApplication.clipboard()
        clipboard.setText(cnt)
        self.card_log.append(f'已复制: {cnt}')

    def copyIDCardMsg(self, key):

        lb = getattr(self, f'id_{key}')
        if isinstance(lb, QLabel):
            cnt = lb.text()
        else:
            cnt = ''
        if cnt.lower() != 'none':
            clipboard = QApplication.clipboard()
            clipboard.setText(cnt)
            self.card_log.append(f'{key}: {cnt} -- 已复制')




